package i18nit

import grails.validation.ValidationException
import org.springframework.context.MessageSource

import static org.springframework.http.HttpStatus.*

class EmployeeController {
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    MessageSource messageSource

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Employee.list(params), model: [employeeCount: Employee.count()]
    }

    def show(Long id) {
        respond Employee.get(id)
    }

    def save(Employee employee) {
        if (employee == null) {
            render status: NOT_FOUND
            return
        }

        employee.save(flush: true)

        if (employee.hasErrors()) {
            employee.errors.allErrors.each {
                println "[controller]" + messageSource.getMessage(it, request.locale)
            }
            respond employee.errors, view: 'create'
            return
        }

        respond employee, [status: CREATED, view: "show"]
    }

    def update(Employee employee) {
        if (employee == null) {
            render status: NOT_FOUND
            return
        }

        try {
            employee.save(flush: true)
        } catch (ValidationException e) {
            respond employee.errors, view: 'edit'
            return
        }

        respond employee, [status: OK, view: "show"]
    }

    def delete(Long id) {
        if (id == null) {
            render status: NOT_FOUND
            return
        }

        Employee.get(id).delete(flush: true)

        render status: NO_CONTENT
    }
}
